package com.cc.comm.responce;

import com.cc.comm.api.ResultCode;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

/**
 * @author CC
 * @version 1.0
 * @description: 统一返回结果类
 * @date 2025/9/11 15:30
 */
@Data
@Schema(description = "统一返回结果类")
public class R<T> {
    //状态码
    @Schema(description = "状态码")
    private Integer code;
    //消息
    @Schema(description = "消息")
    private String message;
    //数据
    @Schema(description = "数据")
    private T data;
    //时间
    @Schema(description = "时间")
    private Long timestamp;
    //状态
    @Schema(description = "状态")
    private Boolean status;

    private R(ResultCode resultCode) {
        this.code = resultCode.getCode();
        this.message = resultCode.getMessage();
        this.timestamp = System.currentTimeMillis();
        this.status = resultCode.getCode() == ResultCode.SUCCESS.getCode(); // 自动判断
    }

    private R(ResultCode resultCode, T data) {
        this.code = resultCode.getCode();
        this.message = resultCode.getMessage();
        this.data = data;
        this.timestamp = System.currentTimeMillis();
        this.status = resultCode.getCode() == ResultCode.SUCCESS.getCode(); // 自动判断
    }

    /**
     * 静态工厂方法
     * 成功 - 无数据
     */
    public static <T> R<T> success() {
        return new R<>(ResultCode.SUCCESS);
    }

    /**
     * 成功 - 有数据
     */
    public static <T> R<T> success(T data) {
        return new R<>(ResultCode.SUCCESS, data);
    }

    // 通用失败：自定义 code + message
    public static <T> R<T> fail(Integer code, String message) {
        R<T> result = new R<>(ResultCode.FAIL);
        result.setCode(code);
        result.setMessage(message);
        result.setStatus(false);
        return result;
    }

    /**
     * 失败 - 使用默认错误码（500）
     */
    public static <T> R<T> fail() {
        return new R<>(ResultCode.FAIL);
    }

    /**
     * 失败 - 自定义错误信息（使用 500 码，但消息不同）
     */
    public static <T> R<T> fail(String message) {
        R<T> result = new R<>(ResultCode.FAIL);
        result.setMessage(message); // 覆盖默认消息
        return result;
    }

    /**
     * 指定错误码返回
     */
    public static <T> R<T> fail(ResultCode resultCode) {
        return new R<>(resultCode);
    }

    /**
     * 参数校验失败
     */
    public static <T> R<T> validateFail(String message) {
        R<T> result = new R<>(ResultCode.VALIDATE_FAILED);
        result.setMessage(message);
        return result;
    }
}
